package com.yox.rpc.hook;

import com.yox.rpc.factory.ThreadPoolFactory;
import com.yox.rpc.util.NacosUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class ShutdownHook {

    private static final Logger logger = LoggerFactory.getLogger(ShutdownHook.class);

    private volatile static ShutdownHook shutdownHook;

    public static ShutdownHook getShutdownHook() {
        if (shutdownHook == null) {
            synchronized (ShutdownHook.class) {
                if (shutdownHook == null)
                    shutdownHook = new ShutdownHook();
            }
        }
        return shutdownHook;
    }

    // 注销服务的钩子
    public void addClearAllHook() {
        logger.info("服务端关闭前将自动注销所有服务");
        Runtime.getRuntime().addShutdownHook(new Thread(() -> {
            // 注销服务
            NacosUtil.clearRegistry();
            // 关闭钩子启动的线程池
            ThreadPoolFactory.shutDownAll();
        }));
    }
}
